import { useMemberStore } from "@/stores";
const memberStore = useMemberStore();

const baseURL = 'http://localhost:7071/user'; // 确保 URL 是完整的

// 请求拦截器
const requestInterceptors = [];
const responseInterceptors = [];

// 添加请求拦截器
function addRequestInterceptor(interceptor) {
  requestInterceptors.push(interceptor);
}

// 添加响应拦截器
function addResponseInterceptor(interceptor) {
  responseInterceptors.push(interceptor);
}

const request = (options) => {
  return new Promise((resolve, reject) => {
    // 应用请求拦截器
    let modifiedOptions = options;
    for (const interceptor of requestInterceptors) {
      modifiedOptions = interceptor(modifiedOptions);
    }

    // 获取 token 并添加到请求头
    const token = memberStore.profile?.token;
    const headers = {
      'content-type': 'application/json',
      ...(modifiedOptions.header || {}),
    };
    if (token) {
      headers['Authorization'] = `Bearer ${token}`;
    }

    uni.request({
      url: baseURL + modifiedOptions.url,
      method: modifiedOptions.method || 'GET',
      data: modifiedOptions.data || {},
      header: headers,
      success: (res) => {
        // 应用响应拦截器
        let modifiedResponse = res;
        for (const interceptor of responseInterceptors) {
          modifiedResponse = interceptor(modifiedResponse);
        }

        if (modifiedResponse.statusCode === 200) {
          if (modifiedResponse.data.code === 1) {
            resolve(modifiedResponse.data);
          } else {
            uni.showToast({
              title: modifiedResponse.data.message || '服务异常',
              icon: 'none',
            });
            reject(modifiedResponse.data);
          }
        } else {
          uni.showToast({
            title: '请求失败',
            icon: 'none',
          });
          reject(modifiedResponse);
        }
      },
      fail: (err) => {
        uni.showToast({
          title: err.errMsg || '服务异常',
          icon: 'none',
        });
        console.log(err);
        if (err.statusCode === 401) {
          uni.navigateTo({
            url: '/pages/login/login',
          });
        }
        reject(err);
      },
    });
  });
};

// 导出拦截器添加方法
export { addRequestInterceptor, addResponseInterceptor };

export default request;
export { baseURL };